package com.pda.yuanjing.pages.custombill.scanf;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanout.JDListBeanOut;
import com.pda.yuanjing.beanout.NoBillBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.error.ErrorDialog;
import com.pda.yuanjing.message.MessageBus;
import com.pda.yuanjing.thread.CodeBeans;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.dialogs.ChooseDialog;
import com.public_module.tools.DensityUtil;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ListScanfActivity extends BaseActivity<ScanfModel, ScanfView, ScanfPresent> implements ScanfView {
    @BindView(R.id.tvlc)
    TextView tvlc;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.tvjd)
    TextView tvjd;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.tvkf)
    TextView tvkf;
    @BindView(R.id.ll3)
    LinearLayout ll3;
    @BindView(R.id.tvgys)
    TextView tvgys;
    @BindView(R.id.ll4)
    LinearLayout ll4;
    @BindView(R.id.tvjxs)
    TextView tvjxs;
    @BindView(R.id.ll5)
    LinearLayout ll5;
    @BindView(R.id.lls)
    LinearLayout lls;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvzs)
    TextView tvzs;
    @BindView(R.id.ivs)
    ImageView ivs;
    @BindView(R.id.tvc1)
    TextView tvc1;
    @BindView(R.id.vline)
    View vline;
    @BindView(R.id.tvzsv)
    TextView tvzsv;
    @BindView(R.id.tvbatchNo)
    TextView tvbatchNo;
    @BindView(R.id.tvbatchNov)
    TextView tvbatchNov;
    @BindView(R.id.tvcd)
    TextView tvcd;
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.ivd)
    ImageView ivd;
    @BindView(R.id.tvjc)
    TextView tvjc;
    @BindView(R.id.etres)
    TextView etres;
    @BindView(R.id.tvres)
    TextView tvres;
    @BindView(R.id.tvs)
    TextView tvs;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tvwait)
    TextView tvwait;

    private String TAG = "ListScanfActivity";
    private OptionsPickerView pickerView;
    int scanfState = 0;
    boolean flag = true;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    JDListBeanOut dataBean = null;
    //    List<JDBeanOut.DataBean.ListFormBaseListBean.ListSelectBean> tlist = new ArrayList<>();
    String key = "";
    List<Integer> codeNums = new ArrayList<>();
    String codes = "";
    int index = 0;
    CodeBeans codeBeans = new CodeBeans();
    List<JDListBeanOut.DataBean> listStr = new ArrayList<>();
    int waitNum = 0;
    Thread upThread = null;
    boolean exit = false;
    ProductAdapter productAdapter;
    String billListID = "-1";
    int pIndex = -1;
    ErrorDialog errorDialog;

    protected void initdata() {
        dataBean = (JDListBeanOut) getIntent().getSerializableExtra(PDApp.process);
        tvTitle.setText(dataBean.getJieDianName() + " " + SharedPreferencesManger.getRealName());
        tvzs.setText(dataBean.getJieBeiZhu());
        Glide.with(mContext).load(dataBean.getJieImage()).into(ivs);
        tvwait.setText(waitNum + "");
        codeNums = dataBean.getListCodeNums();
        if (codeNums.size() > 0) {
            tvc1.setText("当前应扫" + codeNums.get(index) + "位数码");
        }
//        chooseDialog = new ChooseDialog(this, "是否开启删除条码", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
//            @Override
//            public void setActivityText() {
//                chooseDialog.dismiss();
//                flag = false;
//                ivd.setImageResource(R.mipmap.icon_check);
//            }
//        });
//        WindowManager.LayoutParams lp = chooseDialog.getWindow().getAttributes();
//        lp.gravity = Gravity.CENTER;

        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                        tvs.setText(dataa.getStr());
                        scanfState = dataa.getType();
                        if (scanfState == -1) {
                            tvs.setBackgroundResource(R.color.smalltext);
                        } else {
                            tvs.setBackgroundResource(R.color.green);
                        }
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        if (!PDApp.scanf) {
                            return;
                        }
                        if (scanfState == -1) {
                            showres("网络异常,请检查网络");
//                            voiceUtils.voiceWarn();
//                            tvres.setText("网络异常,请检查网络");
                            return;
                        }
                        if (billListID.equals("-1") && dataBean.getSelectProduct()) {
                            showres("请选中产品");
//                            voiceUtils.voiceWarn();
//                            tvres.setText("请选中产品");
                            return;
                        }
                        String ss = StringProcess.codeMat(string);
                        CodeBeans.Code cbean = new CodeBeans.Code();
                        cbean.setStr(ss);
                        cbean.setFlag(flag);
                        codeBeans.addCode(cbean);
                        tvwait.setText(codeBeans.getCodes().size() + "");
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        upThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!exit) {
                    if (codeBeans!=null && codeBeans.getCodes().size() > 0) {
                        try {
                            presenter.scanfCode2(dataBean.getBatchID(), billListID, codeBeans.getCodes().get(0).getStr(), key, codeBeans);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        upThread.start();
        listStr = dataBean.getData();
        productAdapter = new ProductAdapter(this, listStr);
        listview.setAdapter(productAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_controllist_scanf);
        ButterKnife.bind(this);
        initdata();
        EventBus.getDefault().register(this);
        if (!StringProcess.stringIsZero(dataBean.getProcessName())) {
            ll1.setVisibility(View.VISIBLE);
            tvlc.setText(dataBean.getProcessName());
        } else {
            ll1.setVisibility(View.GONE);
        }
        if (!StringProcess.stringIsZero(dataBean.getJieDianName())) {
            ll2.setVisibility(View.VISIBLE);
            tvjd.setText(dataBean.getJieDianName());
        } else {
            ll2.setVisibility(View.GONE);
        }
        if (!StringProcess.stringIsZero(dataBean.getStoreIDIn())) {
            ll3.setVisibility(View.VISIBLE);
            tvkf.setText(dataBean.getStoreIDIn());
        } else {
            ll3.setVisibility(View.GONE);
        }
        if (!StringProcess.stringIsZero(dataBean.getGongYingShangName())) {
            ll4.setVisibility(View.VISIBLE);
            tvgys.setText(dataBean.getGongYingShangName());
        } else {
            ll4.setVisibility(View.GONE);
        }
        if (!StringProcess.stringIsZero(dataBean.getDealerName())) {
            ll5.setVisibility(View.VISIBLE);
            tvjxs.setText(dataBean.getDealerName());
        } else {
            ll5.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
        EventBus.getDefault().unregister(this);
        exit = true;
        upThread = null;
    }

    @Override
    public ScanfModel createModel() {
        return new ScanfModelImpl(this);
    }

    @Override
    public ScanfView createView() {
        return this;
    }

    @Override
    public ScanfPresent createPresenter() {
        return new ScanfPresent();
    }


    @OnClick({R.id.iv_title_left, R.id.logine, R.id.etres, R.id.ivd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.ivd:
                if (flag) {
                    chooseDialog.show();
                } else {
                    flag = true;
                    ivd.setImageResource(R.mipmap.icon_nocheck);
                }
                break;
            case R.id.logine:
//                if (scanfState == -1) {
//                    voiceUtils.voiceWarn();
//                    tvres.setText("网络异常,请检查网络");
//                    return;
//                }
//                if (billListID.equals("-1")) {
//                    voiceUtils.voiceWarn();
//                    tvres.setText("请选中产品");
//                    return;
//                }
                if (scanfState == -1) {
                    showres("网络异常,请检查网络");
                    return;
                }
                if (billListID.equals("-1") && dataBean.getSelectProduct()) {
                    showres("请选中产品");
                    return;
                }
                CodeBeans.Code cbean = new CodeBeans.Code();
                cbean.setStr(loginId.getText().toString());
                cbean.setFlag(flag);
                codeBeans.addCode(cbean);
                tvwait.setText(codeBeans.getCodes().size() + "");
                break;
            case R.id.etres:
                pickerView.show();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void showres(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                voiceUtils.voiceWarn();
                tvres.setText(str);
                loginId.setText("");
                tvwait.setText(codeBeans.getCodes().size() + "");
                if (PDApp.cidInfoBeanOut.getData()!=null && PDApp.cidInfoBeanOut.getData().isShowErrorDialog()) {
                    errorDialog = new ErrorDialog(mContext, str, R.style.CommentDialog, new ErrorDialog.PriorityListener() {
                        @Override
                        public void setActivityText() {
                        }
                    });
                    WindowManager.LayoutParams lp = errorDialog.getWindow().getAttributes();
                    lp.gravity = Gravity.CENTER;
                    errorDialog.show();
                    Window window = errorDialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams attrs = window.getAttributes();
                    attrs.width = (int) DensityUtil.dp2px(ListScanfActivity.this, 300);
                    attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    errorDialog.getWindow().setAttributes(attrs);
                }
            }
        });
    }

    @Override
    public void showSuccessres(JDListBeanOut jdListBeanOut) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvres.setText("数码处理完成");
                loginId.setText("");
                tvwait.setText(codeBeans.getCodes().size() + "");
                listStr.clear();
                listStr.addAll(jdListBeanOut.getData());
                if (pIndex != -1) {
                    listStr.get(pIndex).setCk(true);
                }
                productAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onshowSuccessresNoBill(NoBillBeanOut.DataBean codeInfoBean) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageBus messageBus) {
        for (int i = 0; i < listStr.size(); i++) {
            listStr.get(i).setCk(false);
        }
        if (messageBus.getValue() == 1) {
            listStr.get(messageBus.getIndex()).setCk(true);
            billListID = listStr.get(messageBus.getIndex()).getBillListID();
            pIndex = messageBus.getIndex();
        } else {
            listStr.get(messageBus.getIndex()).setCk(false);
            billListID = "-1";
            pIndex = -1;
        }
        productAdapter.notifyDataSetChanged();
    }
}
